package com.woniu.woniuticket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rabbitmq.client.Channel;
import com.woniu.woniuticket.config.RabbitConfig;
import com.woniu.woniuticket.dao.SeatMapper;
import com.woniu.woniuticket.dao.ShowSessionMapper;
import com.woniu.woniuticket.entity.*;
import com.woniu.woniuticket.dao.OrderMapper;
import com.woniu.woniuticket.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.woniuticket.untils.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shaotianjing
 * @since 2020-01-02
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderForm> implements IOrderService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private SnowFlake snowFlake;

    @Autowired
    private OrderMapper om;

    @Autowired
    private SeatMapper sm;

    @Autowired
    private ShowSessionMapper ssm;

    private static long size=10;
    @Override
    public List<OrderAllInfo> getOrder(Integer studentId) {
        System.out.println(om.getOrder(studentId));
        List<OrderAllInfo> res = om.getOrder(studentId);
        return res;
    }

    @Override
    public int delOrder(Integer orderId) {
        return om.delOrder(orderId);
    }

    @Override
    public int remoney(Integer orderId) {
        Date date = new Date();
        System.out.println(date);
        OrderForm of = om.selectById(orderId);
        System.out.println(of.toString());
        ShowSession showSession = ssm.selectById(of.getShowSessionId());
        System.out.println(showSession.toString());

        return om.remoney(orderId);
    }

    @Override
    public int qrorder(Integer orderId) {
        return om.qrorder(orderId);
    }

    @Override
    public int selectOrder(Integer orderId) {
        return om.selectOrder(orderId);
    }

    //队列15分钟订单
    @Override
    public OrderForm productOrder(Integer studentId, BigDecimal orderPrice, String orderName, List<SelectSeat> selectSeats, String seat, Integer showSessionId, Integer ticketNumber) {

        //调用雪花方法生成订单编号
        long l = snowFlake.nextId();
        Date date = new Date();
        BigDecimal totelPayment = orderPrice.multiply(new BigDecimal(ticketNumber));
        OrderForm orderForm1 = new OrderForm();
        try {
               List<Integer> orderList = new ArrayList<>();
               for(int i = 0 ; i <selectSeats.size() ; i++){
                   //生成订单
                   SelectSeat selectSeat1 = selectSeats.get(i);
                   Integer row = selectSeat1.getRow() + 1;
                   Integer col = selectSeat1.getCol() + 1;
                   String seatNum = row + "," + col;
                   OrderForm orderForm = new OrderForm();
                   orderForm.setOrderNo(l+"");
                   orderForm.setOrderTime(date);
                   System.out.println("订单编号是："+orderForm.getOrderNo()+"~~~~ 日期："+orderForm.getOrderTime());
                   orderForm.setOrderName(orderName);
                   orderForm.setOrderPrice(orderPrice);
                   orderForm.setShowSessionId(showSessionId);
                   orderForm.setStudentId(studentId);
                   orderForm.setTicketNumber(ticketNumber);
                   orderForm.setTotelPayment(totelPayment);
                   orderForm.setSeatId(seatNum);
                   System.out.println("orderForm："+orderForm.toString());
                   int productresult = om.productOrder(orderForm);
                   System.out.println("生成订单结果："+productresult);

                   orderList.add(orderForm.getOrderId());
               }
                System.out.println("集合长度："+orderList.toString());
                //修改seatbuy座位状态
               int updateresult = sm.updateSeatBuy(showSessionId,seat);
               System.out.println("座位状态："+updateresult);
               //订单放入队列中，同时设置15分钟死信
                for(int j = 0 ; j <orderList.size();j++){
                    this.amqpTemplate.convertAndSend(RabbitConfig.ORDER_DELAY_EXCHANGE,RabbitConfig.ORDER_DELAY_ROUTING_KEY,orderList.get(j),
                            message -> {message.getMessageProperties().setExpiration(15* 1000 * 60 + "");
                                return message;
                            });
                    System.out.println(orderList.get(j).toString());
                }
                //查看订单信息
                orderForm1 = om.findSomeOrder(orderList.get(0));
        }catch (Exception e){
            //生成订单失败，此场次此座位不可用，返回前端结果为0
            e.printStackTrace();
        }
        return orderForm1;
    }
    @Override
    public List<String> findByOutTradeNo(String out_trade_no) {
        return om.findByOrderNo(out_trade_no);
    }

    @Override
    public int payMoney(String of) {
        System.out.println(of+"支付宝回调~这是订单编号");
        return om.payMoney(of);
    }

    @Override
    public int findSomeOrder(Integer orderId) {
        return om.selectOrder(orderId);
    }

    @Override
    public String findOrderTime(Integer orderId) {
        OrderForm of = om.findSomeOrder(orderId);
        //获取订单时间
        Date ordertime = of.getOrderTime();
        Date date = new Date();
        long time = 15*60*1000-(date.getTime()-ordertime.getTime());
        long min = time/1000/60;
        log.info("分钟："+min);
        long s  = (time - min*60*1000)/1000;
        log.info("秒："+s);
        String result = "";
        result = min+":"+s;
        return result;
    }
    @Override
    public IPage<OrderForm> selectOrderByStatus(Page<OrderForm> ordersPage,Form form) {
        QueryWrapper<OrderForm> oqw = new QueryWrapper<>();
        String status = form.getStatus();
        LocalDateTime[] time = form.getTime();
        if (status!=null && !status.equals("")){
            oqw.eq("order_status",status);
        }
        if(time.length>0){
            oqw.ge("order_time",time[0]).le("order_time",time[1]);
        }
        return om.selectPage(ordersPage, oqw);

    }
    /*//监听消息队列
    @RabbitListener(queues = {RabbitConfig.ORDER_QUEUE_NAME})
    public void consumeMessage(Integer orderId, Message message, Channel channel) throws IOException {
        try {
            //查询订单状态
            log.info("死信id："+orderId);
            //log.info("死信队列：seatid:"+order.getSeatId()+"~~~~~showsessionid:"+order.getShowSessionId());
            OrderForm result = om.findSomeOrder(orderId);
            System.out.println("死信订单状态："+result.getOrderStatus());
            if(result.getOrderStatus()==1){
                System.out.println("查询订单状态为未付款时");
                //修改seatbuy表里面的座位状态
                //找到坐标
                String seat =result.getSeatId();
                String[] split1 = seat.split(",");
                int row = Integer.valueOf(split1[0]) - 1;
                int col = Integer.valueOf(split1[1]) - 1;
                //获取此时此刻seatbuy的座位
                String videoHallTableByMovieTicketIdPc = sm.getAllSeat(result.getShowSessionId());
                String[] split = videoHallTableByMovieTicketIdPc.split(",");
                String s = split[row];
                String seatBack = null;
                if (col == s.length() - 1) {
                    seatBack = s.substring(0, col) + "1";
                } else {
                    seatBack = s.substring(0, col) + "1" + s.substring(col + 1, s.length());
                }
                split[row] = seatBack;
                String res = "";
                for (int i = 0; i < split.length; i++) {
                    res += split[i] + ",";
                }
                res = res.substring(0, res.length() - 1);
                //将座位替换seatbuy的座位
                int a = sm.updateSeatBuy(result.getShowSessionId(),res);
                System.out.println("座位是否被替换"+a);
                //修改订单状态以及将订单表里面的座位清空
                System.out.println("死信队列里面的查询结果："+result.getOrderId());
                om.ttlOrder(result.getOrderId());
            }
            //查询订单是否支付，如果未支付则修改订单状态为超时
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
